import {getParamsFromCommand, validProdVersion, versionRegx} from './utils.js'
import inquirer from 'inquirer'
import path from 'path'
import fs from 'fs'
import dayjs from 'dayjs'
import axios from 'axios'
import { fileURLToPath } from 'url'
import genTag from './gen-tag.js'

const { no, version: forceVersion, temp = 0, test = 0 } =getParamsFromCommand(process.argv)


const defConfigUrls = [
     'http://101.132.163.3:10067/pub/defConfig.json',
     'http://101.132.163.3:10068/pub/defConfig.json',
     'http://101.132.163.3:10069/pub/defConfig.json',
     'http://101.132.163.3:10070/pub/defConfig.json',
     'http://101.132.163.3:10076/pub/defConfig.json'
]


const autoGenVersion = () => {
     return new Promise((resolve, reject) => {
          Promise.allSettled(defConfigUrls.map(v => axios.get(`${v}?_t${Date.now()}`, { timeout: 10000 }))).then(resp => {
               const successData = resp.filter(v => v.status === 'fulfilled').map(v => v.value.data)
               const dataStr = dayjs().format('YYMMDD')
               let distType = '9'
               if (temp) {
                    distType = '5'
               }
               if (test) {
                    distType = '3'
               }
               const firstPart = `${dataStr}${distType}`
               console.log('--------------------service version--------------------')
               console.log(successData.map((v, i) => `${defConfigUrls[i]}: ${v.VERSION}`).join('\n'))
               console.log('-------------------------------------------------------')
               const versionList = successData
                   .map((v, i) => ({ version: v.VERSION, service: defConfigUrls[i] }))
                   .filter(v => {
                        return versionRegx.test(v.version) && new RegExp(`${dataStr}\\d.`).test(v.version)
                   })
               const manualNo = isNaN(Number(no)) ? 0 : Number(no)
               const max = Math.max(...versionList.map(v => Number(v.version.split('.')[1])), 0)
               const finallyNo = manualNo > max ? manualNo : max + 1
               const version = [firstPart, String(finallyNo).padStart(2, '0')].join('.')
               console.log('oldVersion in service')

               resolve(version)
          })
     })
}

const genVersion = async() =>{
     // 手动指定
     if (forceVersion) {
          console.log('使用用户指定的版本号', forceVersion)
          return forceVersion
     }
     // 自动生成
     const autoVersion = await autoGenVersion()
     // 验证版本号是不是符合规范
     const answer = await inquirer.prompt([
          {
               type: 'input',
               name: 'version',
               required: true,
               default: autoVersion,
               validate: v => {
                    if (versionRegx.test(v)) {
                         return true
                    } else {
                         return '版本号不符合规范'
                    }
               }
          }
     ])
     return answer.version

}
const __dirname = path.join(path.dirname(fileURLToPath(import.meta.url)),'../')
const writeFiles = (version) =>{
     console.log(process.cwd(),'llll')
     const defConfigPath = path.resolve(process.cwd(), 'public/pub/defConfig.json')
     const isProdVersion = validProdVersion(version)
     const newDefConfigStr =
         JSON.stringify(
             {
                  VERSION: version,
                  env: isProdVersion ? 'prod' : 'test'
             },
             null,
             4
         ) + '\n'
     fs.writeFileSync(defConfigPath, newDefConfigStr)

}

genVersion().then(version=>{
     // 写入config文件
     writeFiles(version)
     console.log(`defConfig.json 写入 version "${version}" 成功`)
     //打tag标签
     // genTag(version)
})
